/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sunrise.boundary;

import com.sunrise.entity.Event;
import com.sunrise.entity.InvitationRequest;
import com.sunrise.entity.User;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.persistence.TransactionRequiredException;

/**
 *
 * @author frank
 */
@Stateless
public class InvitationRequestManager extends GenericManager<InvitationRequest> {
    
    @PostConstruct
    private void init() {
        super.typeParameterClass = InvitationRequest.class;
    }
    
    public InvitationRequest findInvitationRequest(Event e, User recipient) {
        if (e.getCalendar() == null) return null;
        
        Map params = new HashMap<>();
        params.put("recipient", recipient);
        params.put("event", e);
        InvitationRequest r = super.findOneWithNamedQuery(InvitationRequest.findByRecipientAndEvent, params);
        return r;
    }
    
    public void deleteInvitationRequestsForEvent(Event e) {
        Map params = new HashMap<>();
        params.put("event", e);
        List<InvitationRequest> res = findManyWithNamedQuery(InvitationRequest.findByEvent, params);
        for (InvitationRequest r : res) {
            InvitationRequest persistedEntity = entityManager.getReference(typeParameterClass, r.getId());
            entityManager.remove(persistedEntity);
        }
    }
    
    public boolean delete(InvitationRequest ir) {
        try {
            InvitationRequest persistedEntity = entityManager.getReference(InvitationRequest.class, ir.getId());
            entityManager.remove(persistedEntity);
        } catch (TransactionRequiredException | IllegalArgumentException ex) {
            return false;
        }
        
        return true;
    }
    
    public List<User> invitedUsers(List<InvitationRequest> requests) {
        if (requests == null) return null;
        
        List <User> res = new ArrayList<>();
        for (InvitationRequest request : requests) {
            res.add(request.getRecipient());
        }
        
        return res;
    }
}
